import React, { useRef, useState, useEffect, useCallback } from "react";
import { Tabs, Swiper, SearchBar, Ellipsis, SideBar } from "antd-mobile";
import { indexList, topList, categoryList } from "@/apis/api";
import "./home.less";
import { useThrottleFn } from "ahooks";

function Tablist() {
  const tabItems = [
    { key: "fruits", title: "推荐" },
    { key: "vegetables", title: "榜单" },
    { key: "animals", title: "分类" },
  ];
  const tabHeight = 42;
  const swiperRef = useRef(null);
  const [activeIndex, setActiveIndex] = useState(0);
  return (
    <div className="Tablist">
      <div className="Tablist-title">
        <div className="tablist">
          <Tabs
            activeKey={tabItems[activeIndex].key}
            onChange={(key) => {
              const index = tabItems.findIndex((item) => item.key === key);
              setActiveIndex(index);
              swiperRef.current?.swipeTo(index);
              window.scrollTo({
                top: window.scrollY - tabHeight,
              });
            }}
          >
            {tabItems.map((item) => (
              <Tabs.Tab title={item.title} key={item.key} />
            ))}
          </Tabs>
        </div>
        <div className="search">
          <SearchBar placeholder="请输入搜索内容" />
        </div>
      </div>
      <div className="Tablist-content">
        <Swiper
          direction="horizontal"
          indicator={() => null}
          ref={swiperRef}
          defaultIndex={activeIndex}
          onIndexChange={(index) => {
            setActiveIndex(index);
          }}
        >
          <Swiper.Item>
            <Banner></Banner>
            <ListDemo></ListDemo>
          </Swiper.Item>
          <Swiper.Item>
            <SideBarList />
          </Swiper.Item>
          <Swiper.Item>
            <ClassFiyList />
          </Swiper.Item>
        </Swiper>
      </div>
    </div>
  );
}
//轮播图组件
function Banner() {
  const recommend = [
    {
      type: 1,
      did: 2100,
      chapterid: 0,
      src: "http://ksyuncomic.9comic.cn/comic/2024/01/05/02814a789243b6f3fe4d131093b672a4.jpg",
      width: 784,
      height: 543,
      url: "",
      title: "",
      desc: "",
    },
    {
      type: 1,
      did: 2087,
      chapterid: 0,
      src: "http://ksyuncomic.9comic.cn/comic/2023/10/04/0020e332b2184493dbc335507c2c9eeb.jpg",
      width: 720,
      height: 552,
      url: "",
      title: "",
      desc: "",
    },
    {
      type: 1,
      did: 162,
      chapterid: 0,
      src: "http://ksyuncomic.9comic.cn/comic/2019/05/09/3c73282d9e3399b7a37f0ff2ae7447fe.jpg",
      width: 720,
      height: 568,
      url: "",
      title: "",
      desc: "",
    },
    {
      type: 1,
      did: 103,
      chapterid: 0,
      src: "http://ksyuncomic.9comic.cn/comic/2019/04/10/43748157489a32e35f8858da65e658f4.jpg",
      width: 1080,
      height: 852,
      url: "",
      title: "",
      desc: "",
    },
    {
      type: 1,
      did: 164,
      chapterid: 0,
      src: "http://ksyuncomic.9comic.cn/comic/2019/04/10/fc7a5a0ca9fd0bb929b48c426791869f.jpg",
      width: 720,
      height: 516,
      url: "",
      title: "",
      desc: "",
    },
  ];

  return (
    <div className="banner">
      <Swiper
        loop
        onIndexChange={(i) => {
          // console.log(i, "onIndexChange1");
        }}
      >
        {recommend.map((item, index) => {
          return (
            <Swiper.Item key={index}>
              <div className="item-img">
                <img src={item.src} alt="" />
              </div>
            </Swiper.Item>
          );
        })}
      </Swiper>
    </div>
  );
}
// 榜单列表
function SideBarList() {
  // 定义榜单数据类型
  interface RankData {
    key: string;
    title: string;
    data: any; // 可以进一步定义更具体的类型
  }
  // 定义当前激活的榜单
  const [activeKey, setActiveKey] = useState("1");
  // 定义榜单列表
  const [rankingList, setRankingList] = useState<RankData[]>([]);
  // 定义榜单标题列表
  const titleList = [
    {
      id: "1",
      title: "人气榜",
      key: "1",
    },
    {
      id: "4",
      title: "男生榜",
      key: "2",
    },
    {
      id: "5",
      title: "女生榜",
      key: "3",
    },
    {
      id: "2",
      title: "新作榜",
      key: "4",
    },
    {
      id: "6",
      title: "催更榜",
      key: "5",
    },
  ];

  // 获取榜单数据
  const topListApi = async () => {
    // topList({ id: activeKey, p: 1 }).then((res) => {
    //   console.log(res.data);
    //   setRankingList(res.data);
    // });
    try {
      const lists: RankData[] = [];
      // 并行请求所有榜单数据
      const promises = titleList.map((item) =>
        topList({ id: item.id, p: 1 }).then((res) => {
          let data = {
            key: item.key,
            title: item.title,
            data: res.data,
          };
          lists.push(data);
        })
      );

      await Promise.all(promises);
      lists.sort((a, b) => parseInt(a.key) - parseInt(b.key));
      setRankingList(lists);

      // 设置默认激活的榜单
      if (lists.length > 0) {
        setActiveKey(lists[0].key);
      }
    } catch (error) {
      console.error("获取榜单数据失败:", error);
    }
  };
  // 监听滚动事件，设置当前激活的榜单
  const { run: handleScroll } = useThrottleFn(
    () => {
      let currentKey = titleList[0].key;
      for (const item of titleList) {
        const element = document.getElementById(`anchor-${item.key}`);
        if (!element) continue;
        const rect = element.getBoundingClientRect();
        if (rect.top <= 100) {
          currentKey = item.key;
        } else {
          break;
        }
      }
      setActiveKey(currentKey);
    },
    {
      leading: true,
      trailing: true,
      wait: 100,
    }
  );

  // 定义主元素引用
  const mainElementRef = useRef<HTMLDivElement>(null);
  // 组件挂载时获取榜单数据，并监听滚动事件
  useEffect(() => {
    topListApi();
    const mainElement = mainElementRef.current;
    if (!mainElement) return;
    mainElement.addEventListener("scroll", handleScroll);
    return () => {
      mainElement.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div className="sideList">
      <div className="left">
        <SideBar
          activeKey={activeKey}
          onChange={(key) => {
            document.getElementById(`anchor-${key}`)?.scrollIntoView();
            // scrollToInParent(`anchor-${key}`);
          }}
        >
          {titleList.map((item) => (
            <SideBar.Item key={item.key} title={item.title} />
          ))}
        </SideBar>
      </div>
      <div className="right" ref={mainElementRef}>
        {rankingList.map((item) => (
          <div key={item.key} className="right_item">
            <h2 id={`anchor-${item.key}`}>{item.title}</h2>
            <div className="list">
              {item.data.map((items) => {
                return (
                  <div className="item" key={items.id}>
                    <div className="img">
                      <img src={items.pic} alt="" />
                    </div>
                    <div className="info">
                      <h3>{items.title}</h3>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
// 定义一个名为ClassFiyList的函数组件
const ClassFiyList: React.FC = () => {
  interface CategoryItem {
    id: number | string;
    title: string;
  }

  interface CategoryData {
    [key: string]: CategoryItem[];
  }
  const [categoryData, setCategoryData] = useState<CategoryData>({});
  const [categoryTypes, setCategoryTypes] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);

        // 模拟API请求返回的数据
        const mockData = {
          category: [
            {
              id: 1,
              title: "都市",
            },
            {
              id: 2,
              title: "恋爱",
            },
            {
              id: 3,
              title: "爆笑",
            },
            {
              id: 4,
              title: "热血",
            },
            {
              id: 5,
              title: "悬疑",
            },
            {
              id: 6,
              title: "古风",
            },
            {
              id: 7,
              title: "校园",
            },
            {
              id: 9,
              title: "搞笑",
            },
            {
              id: 10,
              title: "玄幻",
            },
            {
              id: 11,
              title: "励志",
            },
            {
              id: 13,
              title: "恐怖",
            },
            {
              id: 14,
              title: "冒险",
            },
            {
              id: 15,
              title: "儿童",
            },
          ],
          end: [
            {
              id: "0",
              title: "全部",
            },
            {
              id: "1",
              title: "连载",
            },
            {
              id: "2",
              title: "完结",
            },
          ],
          free: [
            {
              id: "0",
              title: "全部",
            },
            {
              id: "1",
              title: "免费",
            },
            {
              id: "2",
              title: "免费",
            },
          ],
          sort: [
            {
              id: "0",
              title: "最新",
            },
            {
              id: "1",
              title: "最热",
            },
          ],
        };
        const allOption = { id: "0", title: "全部" };
        // 只在 category 和 sort 里插入
        mockData.category.unshift(allOption);
        mockData.sort.unshift(allOption);
        // 获取分类类型（category和end）
        const types = Object.keys(mockData);
        setCategoryTypes(types);
        for (let index = 0; index < categoryTypes.length; index++) {
          const element = categoryTypes[index];
          mockData[`${element}Index`] = 0;
        }
        console.log("mockData", mockData);

        setCategoryData(mockData);

        // categoryList().then((res) => {
        //   setCategoryData(res.data);
        //   // 获取分类类型（category和end）
        //   const types = Object.keys(res.data);
        //   setCategoryTypes(types);
        // });
      } catch (err) {
        setError("获取分类数据失败");
        console.error("Error fetching category data:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <div className="loading">加载中...</div>;
  if (error) return <div className="error">{error}</div>;
  if (categoryTypes.length === 0)
    return <div className="empty">暂无分类数据</div>;
  return (
    <div className="category-container">
      {categoryTypes.map((type) => (
        <div key={type} className="category-section">
          {/* <h3 className="category-title">{type}</h3> */}
          <div className="category-list">
            {categoryData[type].map((item) => (
              <div key={`${type}-${item.id}`} className="category-item">
                {item.title}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

// 漫画列表
function ListDemo() {
  const [list, setList] = useState([]);
  useEffect(() => {
    indexList().then((res) => {
      setList(res.data.tab);
    });
  }, []);
  if (list.length === 0) {
    let lists = [
      {
        id: "13",
        name: "宝藏·大家正在看",
        pictype: "h",
        list: [
          {
            id: 162,
            cateid: "1,2",
            userid: 0,
            author: "仟绘动漫",
            title: "追夫36计：老公来战!",
            tag: "青春 都市 恋爱",
            info: "她暗恋他多年，他拒绝她多年，用尽36计追求，却发现惹了个大麻烦！这些真的值得吗？ 作品改编自纵横中文网同名小说。",
            pic: "http://ksyuncomic.9comic.cn/comic/2019/07/23/907ecc56f6256b123db19304b3e45c16.jpg",
            bigpic:
              "http://ksyuncomic.9comic.cn/comic/2019/03/04/54e3f962eea1d467516f5ef342cf262a.jpg",
            newpic: "",
            indexpic: "",
            updatepic: "",
            firstchapterid: 2658,
            lastchapter: "第277话 午餐愉快",
            lastNumChapter: "277",
            ifend: 0,
            vip: 1,
            coupon: 0,
            look: 12521423,
            createtime: 1551165996000,
            updatetime: 1579138564301,
            onlinetime: "",
            cpid: 0,
            status: 1,
            num_comment: 656,
            num_love: 8245,
            num_look: 12522405,
            num_fav: 52506,
            if_fav: 0,
            if_love: 0,
            if_update: 0,
            lastReadChapter: {},
            indexsort: 1,
          },
          {
            id: 103,
            cateid: "1,2",
            userid: 0,
            author: "仟绘动漫",
            title: "腹黑少爷撩上我",
            tag: "都市 恋爱",
            info: "本一心想调查父亲的真正死因，随着深入竟牵扯集团黑幕和谋杀血案，更惹上阴冷骄横的腹黑少爷，本世纪最彪女主遇上宇宙级腹黑少爷蹦擦出妖艳旋律……《腹黑少爷撩上我》改编自纵横中文网火爆作者墨春花大大的《权少贪欢，撩婚99天》",
            pic: "http://ksyuncomic.9comic.cn/comic/2019/07/19/4fb817924e1df9c8b81379d92fbb95ac.jpg",
            bigpic:
              "http://ksyuncomic.9comic.cn/comic/2019/03/01/27a5a56681857d58dea45897fa94a495.jpg",
            newpic: "comic/2019/07/19/409e05c81c65f816f834f71fa25572cb.jpg",
            indexpic: "",
            updatepic: "",
            firstchapterid: 311,
            lastchapter: "第137话",
            lastNumChapter: "137",
            ifend: 0,
            vip: 1,
            coupon: 0,
            look: 6982271,
            createtime: 1548746919000,
            updatetime: 1568973396111,
            onlinetime: "",
            cpid: 0,
            status: 1,
            num_comment: 378,
            num_love: 7616,
            num_look: 6982876,
            num_fav: 36085,
            if_fav: 0,
            if_love: 0,
            if_update: 0,
            lastReadChapter: {},
            indexsort: 2,
          },
          {
            id: 1745,
            cateid: "1,2",
            userid: 0,
            author: "慕斯",
            title: "总裁任性宠萌妻",
            tag: "恋爱 霸总",
            info: "夏莫言只把洛梦溪当做她的替身，当夏莫言发现自己爱上洛梦溪时，夏莫言该怎么面对她，当夏莫言发现洛梦溪就是她时，夏莫言还能怎么办，只能宠着她喽。",
            pic: "http://ksyuncomic.9comic.cn/comic/2020/11/20/2ab524ae915ff3baecf312d58b44db93.jpg",
            bigpic:
              "http://ksyuncomic.9comic.cn/comic/2020/11/20/59e5e2957769563560e2b6d8112b1c93.jpg",
            newpic: "",
            indexpic: "",
            updatepic: "",
            firstchapterid: 4813899,
            lastchapter: "第110话 跑了？",
            lastNumChapter: "110",
            ifend: 0,
            vip: 0,
            coupon: 0,
            look: 915008,
            createtime: 1605867646006,
            updatetime: 1623030640902,
            onlinetime: "",
            cpid: 0,
            status: 1,
            num_comment: 59,
            num_love: 1228,
            num_look: 915297,
            num_fav: 9063,
            if_fav: 0,
            if_love: 0,
            if_update: 0,
            lastReadChapter: {},
            indexsort: 3,
          },
          {
            id: 128,
            cateid: "2,7",
            userid: 0,
            author: "仟绘动漫",
            title: "这个总裁有点残",
            tag: "恋爱 校园",
            info: "某天夜晚方怡在高级别墅中被人玷污，而玷污她的人正是和她有千丝万缕联系的林寒。 早在孩童时期初次见面他们之间就注定了一种虐与被虐的关系，直到今天…… 这么多年过去了她的生活会有转机吗？ 他们之间会发生怎样的爱恨情仇？ 仇恨背后的秘密又是什么呢？",
            pic: "http://ksyuncomic.9comic.cn/comic/2019/07/19/f96f7ff0ccc5ff488fa36b19b72346e6.jpg",
            bigpic:
              "http://ksyuncomic.9comic.cn/comic/2019/03/01/d05e65e1709e488ec8c18b02aabfda75.jpg",
            newpic: "",
            indexpic: "",
            updatepic: "",
            firstchapterid: 2055,
            lastchapter: "第143话",
            lastNumChapter: "143",
            ifend: 0,
            vip: 1,
            coupon: 0,
            look: 21304177,
            createtime: 1549947914000,
            updatetime: 1580526900213,
            onlinetime: "",
            cpid: 0,
            status: 1,
            num_comment: 1598,
            num_love: 18022,
            num_look: 21305117,
            num_fav: 91663,
            if_fav: 0,
            if_love: 0,
            if_update: 0,
            lastReadChapter: {
              id: 2055,
              comicid: 128,
              chapter: "1",
              name: "1话",
              sort: 1,
              createtime: 1550129064000,
              updatetime: 1566803309267,
              status: 1,
            },
            indexsort: 4,
          },
          {
            id: 164,
            cateid: "1,2,9",
            userid: 0,
            author: "仟绘动漫",
            title: "最强农民工",
            tag: "都市 恋爱 搞笑",
            info: "一个小小的维修工李青，原本过着普普通通的打工生活，却莫名的被牵扯到大家族的斗争中，而他本人的背后却有着惊天的秘密！！！---漫画改编自纵横中文网同名小说。 ",
            pic: "http://ksyuncomic.9comic.cn/comic/2019/07/19/f39683e2b15e1dcae5af8f66600ed905.jpg",
            bigpic:
              "http://ksyuncomic.9comic.cn/comic/2019/03/04/ed7a66bad4c7abf8c207cab6ee523769.jpg",
            newpic: "comic/2019/08/06/08a9fd5e5c8b9aba88d639822268a1f8.jpg",
            indexpic: "",
            updatepic: "",
            firstchapterid: 2947,
            lastchapter: "第219话 上梁不正下梁歪",
            lastNumChapter: "219",
            ifend: 0,
            vip: 1,
            coupon: 0,
            look: 10746274,
            createtime: 1551165996000,
            updatetime: 1594783575716,
            onlinetime: "",
            cpid: 0,
            status: 1,
            num_comment: 711,
            num_love: 6809,
            num_look: 10746791,
            num_fav: 41387,
            if_fav: 0,
            if_love: 0,
            if_update: 0,
            lastReadChapter: {
              id: 2947,
              comicid: 164,
              chapter: "1",
              name: "1话",
              sort: 1,
              createtime: 1551618159000,
              updatetime: 1551618159000,
              status: 1,
            },
            indexsort: 5,
          },
        ],
      },
    ];
    setList(lists);
  }

  return (
    <div className="list-container">
      {Array.isArray(list) &&
        list.map((item, index) => {
          return (
            <div key={index} className="list-item">
              <div className="title">{item.name}</div>
              <div className="imglist">
                {item.list.map((items, indexs) => {
                  return (
                    <div key={indexs} className="img-item">
                      <div className="img">
                        <img src={items.pic} alt="" />
                      </div>
                      <Ellipsis
                        style={{ wordBreak: "break-word" }}
                        direction="end"
                        content={items.title}
                      />
                      <div className="tags">{items.tag}</div>
                    </div>
                  );
                })}
                {item.list.length % 3 > 1 ? (
                  <div className="img-item"></div>
                ) : null}
              </div>
            </div>
          );
        })}
    </div>
  );
}
export default function Home() {
  return (
    <div className="home">
      <Tablist></Tablist>
    </div>
  );
}
